<template>
  <div class="announcement-container">
    <FeatureHeader img="https://cdn-icons-png.flaticon.com/512/1827/1827379.png" title="公告管理" />
    <div class="toolbar">
      <el-button type="primary" @click="handleAdd">发布公告</el-button>
      <el-select v-model="type" placeholder="类型筛选" style="margin-left: 10px" @change="handleTypeChange">
        <el-option label="全部" value=""></el-option>
        <el-option label="通知" value="notice"></el-option>
        <el-option label="公告" value="announcement"></el-option>
        <el-option label="政策" value="policy"></el-option>
      </el-select>
    </div>

    <el-table :data="announcementList" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="title" label="标题"></el-table-column>
      <el-table-column prop="type" label="类型">
        <template slot-scope="scope">
          <el-tag :type="getTypeTag(scope.row.type)">
            {{ getTypeText(scope.row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="publisher" label="发布人"></el-table-column>
      <el-table-column prop="publishTime" label="发布时间"></el-table-column>
      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 'published' ? 'success' : 'info'">
            {{ scope.row.status === 'published' ? '已发布' : '草稿' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="success" @click="handlePublish(scope.row)" v-if="scope.row.status !== 'published'">发布</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="70%">
      <BaseForm :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型">
            <el-option label="通知" value="notice"></el-option>
            <el-option label="公告" value="announcement"></el-option>
            <el-option label="政策" value="policy"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input type="textarea" v-model="form.content" :rows="10"></el-input>
        </el-form-item>
        <el-form-item label="发布日期" prop="date">
          <el-date-picker v-model="form.date" type="datetime" placeholder="选择发布日期"></el-date-picker>
        </el-form-item>
      </BaseForm>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 预览对话框 -->
    <el-dialog title="公告预览" :visible.sync="previewVisible" width="70%">
      <div class="preview-content">
        <h2>{{ previewData.title }}</h2>
        <div class="preview-info">
          <span>发布人：{{ previewData.publisher }}</span>
          <span>发布时间：{{ previewData.publishTime }}</span>
          <span>类型：{{ getTypeText(previewData.type) }}</span>
        </div>
        <div class="preview-body" v-html="previewData.content"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import FeatureHeader from '@/components/FeatureHeader.vue'
import BaseForm from '@/components/BaseForm.vue'
import { mapState, mapActions } from 'vuex'

export default {
  name: 'AnnouncementList',
  components: { FeatureHeader, BaseForm },
  data() {
    return {
      type: '',
      dialogVisible: false,
      previewVisible: false,
      dialogTitle: '发布公告',
      form: {
        title: '',
        type: '',
        content: '',
        date: ''
      },
      previewData: {},
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        type: [{ required: true, message: '请选择类型', trigger: 'change' }],
        content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
        date: [{ required: true, message: '请选择发布日期', trigger: 'change' }]
      },
      editMode: false
    }
  },
  computed: {
    ...mapState({
      allAnnouncements: state => state.announcement.list // 映射全部公告列表
    }),
    // 根据筛选类型过滤公告列表
    announcementList() {
      if (!this.type) {
        return this.allAnnouncements; // 如果没有选择类型，显示全部
      } else {
        return this.allAnnouncements.filter(announcement => announcement.type === this.type);
      }
    }
  },
  created() {
    this.fetchList()
  },
  methods: {
    ...mapActions({
      fetchList: 'announcement/fetchList',
      addAnnouncement: 'announcement/addAnnouncement',
      editAnnouncement: 'announcement/editAnnouncement',
      deleteAnnouncement: 'announcement/deleteAnnouncement',
      publishAnnouncement: 'announcement/publishAnnouncement'
    }),
    handleTypeChange() {
      // 根据类型筛选数据，不需要再次 fetch list，computed属性会响应变化
      // this.fetchList()
    },
    getTypeTag(type) {
      const tags = {
        notice: 'info',
        announcement: 'success',
        policy: 'warning'
      }
      return tags[type] || 'info'
    },
    getTypeText(type) {
      const texts = {
        notice: '通知',
        announcement: '公告',
        policy: '政策'
      }
      return texts[type] || type
    },
    handleAdd() {
      this.dialogTitle = '发布公告'
      this.editMode = false
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
      this.form = {
        title: '',
        type: '',
        content: '',
        date: ''
      }
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogTitle = '编辑公告'
      this.editMode = true
      this.form = { ...row }
      this.dialogVisible = true
    },
    handlePublish(row) {
      this.$confirm('确认发布该公告?', '提示', {
        type: 'warning'
      }).then(() => {
        this.publishAnnouncement(row.id)
        this.$message.success('发布成功')
      }).catch(() => {
        this.$message.info('已取消发布')
      })
    },
    handleDelete(row) {
      this.$confirm('确认删除该公告?', '提示', {
        type: 'warning'
      }).then(() => {
        this.deleteAnnouncement(row.id).then(() => {
          this.$message.success('删除成功')
        }).catch(error => {
          console.error('删除公告失败:', error)
          this.$message.error('删除失败，请重试')
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const announcementData = { ...this.form }
          if (!this.editMode) {
            announcementData.publisher = '当前用户'
            announcementData.publishTime = new Date().toLocaleString()
            announcementData.status = 'draft'
          }
          if (this.editMode) {
            this.editAnnouncement(announcementData)
            this.$message.success('编辑成功')
          } else {
            this.addAnnouncement(announcementData)
            this.$message.success('保存成功')
          }
          this.dialogVisible = false
        } else {
          this.$message.error('表单验证失败，请检查输入项')
        }
      })
    }
  }
}
</script>

<style scoped>
.announcement-container {
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
}

.preview-content {
  padding: 20px;
}

.preview-info {
  margin: 10px 0;
  color: #666;
}

.preview-info span {
  margin-right: 20px;
}

.preview-body {
  margin-top: 20px;
  line-height: 1.6;
}
</style> 